<template>
	<view class="page-content">
		<default-navbar :pageTitle="formData.enterpriseId ? '编辑企业' : '新增企业'"></default-navbar>
		<view class="page-main">
			<!--  errorType="toast" -->
			<up-form labelPosition="top" :model="formData" ref="formRef" labelWidth='300'
				:labelStyle="{ 'padding-left': '20rpx', 'font-weight': 'bold' }">
				<view class="projectInformation">
					<view class="title">
						<i class="iconfont icon-a-pinghangsibianxing2 red"></i>
						<view class="text">
							合作企业详情
						</view>
						<i class="iconfont icon-a-pinghangsibianxing2 blue"></i>
					</view>
					<view class="main">
						<up-form-item label="企业名称" prop="enterpriseName" required>
							<up-input placeholder="请输入企业名称" v-model="formData.enterpriseName"></up-input>
						</up-form-item>
						<up-form-item label="纳税人识别号" prop="taxpayerIdentificationNumber">
							<up-input placeholder="请输入纳税人识别号"
								v-model="formData.taxpayerIdentificationNumber"></up-input>
						</up-form-item>
						<up-form-item label="企业类型" prop="type" required>
							<uni-data-select :clear="true" style="width: 100%;" placeholder="请选择企业类型"
								v-model="formData.type" :localdata="enterpriseList_data"></uni-data-select>
						</up-form-item>
						<up-form-item label="来源" prop="source" required>
							<uni-data-select :clear="true" style="width: 100%;" placeholder="请选择来源"
								v-model="formData.source" :localdata="enterprise_source_data"></uni-data-select>
						</up-form-item>
						<up-form-item label="业务覆盖区域" prop="area" required>
							<up-input placeholder="请输入业务覆盖区域" v-model="formData.area"></up-input>
						</up-form-item>
						<up-form-item label="可合作业务范围" prop="cooperation" required>
							<up-textarea maxlength='-1' autoHeight placeholder="请输入可合作业务范围(如肿瘤电场)"
								v-model="formData.cooperation"></up-textarea>
						</up-form-item>
					</view>
				</view>
				<view class="projectInformation">
					<view class="title">
						<i class="iconfont icon-a-pinghangsibianxing2 red"></i>
						<view class="text">
							合作企业联系人信息
						</view>
						<i class="iconfont icon-a-pinghangsibianxing2 blue"></i>
					</view>
					<view class="main">
						<up-form-item label="联系人姓名" prop="contactName" required>
							<up-input placeholder="请输入联系人姓名" v-model="formData.contactName"></up-input>
						</up-form-item>
						<up-form-item label="联系人职务" prop="contactTitle" required>
							<!-- <uni-data-select :clear="true" style="width: 100%;" placeholder="请选择联系人职务"
								v-model="formData.contactTitle" :localdata="contactTitleList_data"></uni-data-select> -->
								<up-input placeholder="请输入联系人职务" v-model="formData.contactTitle"></up-input>
						</up-form-item>
						<up-form-item label="联系方式" prop="contactInformation" required>
							<up-input placeholder="请输入联系方式" v-model="formData.contactInformation"></up-input>
						</up-form-item>
						<up-form-item label="办公地" prop="province">
							<view style="width: 100%;" @click="show = true">
								<up-input readonly placeholder="请选择办公地" v-model="formData.province">

								</up-input>
							</view>

						</up-form-item>
					</view>
				</view>
			</up-form>

			<view class="operateRroup add" v-if="!formData.enterpriseId">
				<view class="confirm-addVisitItem operateBtn">
					<up-button text="继续添加项目" iconColor="#fff" @click="confirmHandle('linktoAddProject')"></up-button>
				</view>
				<view class="confirm operateBtn">
					<up-button type="primary" text="完成并提交" color="#393e97"
						@click="confirmHandle('linktoDetailPage')"></up-button>
				</view>
			</view>

			<view class="operateRroup edit" v-else>
				<view class="confirm operateBtn">
					<up-button type="primary" text="提交" color="#393e97"
						@click="confirmHandle('linktoDetailPage')"></up-button>
				</view>
				<view class="confirm-addVisitItem operateBtn" v-if="hasPermission('miniapp:enterprise:delete')">
					<up-button text="删除" type="error" color="red"
						@click="deleteItem(deleteUserItem, formData.enterpriseId, 2)"></up-button>
				</view>
			</view>

		</view>

		<up-picker :closeOnClickOverlay="true" keyName="name" valueName="code" :show="show" ref="uPickerRef"
			:columns="columns" :defaultIndex="addressComputed" @close="show = false" @cancel="show = false"
			@change="changeHandler" @confirm="confirmHandler"></up-picker>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, watch, computed, nextTick, toRef } from "vue"
	import { onLoad } from "@dcloudio/uni-app";
	//组件
	import defaultNavbar from "@/components/defaultNavbar/index.vue";
	//接口
	import type { AddUserParams } from "@/api/addUser/types"
	import { addUser } from "@/api/addUser/index"
	import { enterpriseItem, deleteUserItem } from "@/api/userList/index"
	import { provinceCity } from "@/api/common/index"
	//hooks
	import useViewModel from './hooks/useViewModel'
	import useAppHookds from "@/appHooks/useViewModel"
	
	const {
		rules,
		firstContactDate_visible,
		firstContactDate_confirm,
		showFirstContactDate,

	} = useViewModel()


	let {
		getContactTitleList,
		contactTitleList_data,
		getEnterpriseList,
		enterpriseList_data,
		getEnterpriseSourceList,
		enterprise_source_data,
		deleteItem,
		hasPermission
	} = useAppHookds()




	//表单数据
	let formData = ref<AddUserParams>({
		enterpriseId: '',
		enterpriseName: "",
		taxpayerIdentificationNumber: "",
		type: "",
		area: "",
		cooperation: "",
		contactName: "",
		contactTitle: "",
		contactInformation: "",
		province: ""
	})
	
	
	//form表单
	let formRef = ref(null)
	
	//省市区
	let uPickerRef = ref()
	let show = ref<boolean>(false)
	let columns = ref<any[]>([[], []])
	let init = () : Promise<void> => {
		return new Promise((resolve, reject) => {
			getProvinceCity('0').then((rows : any[]) => {
				columns.value = [rows, []]
				uPickerRef.value.setColumnValues(0, rows)
				let { code } = rows[0]
				getProvinceCity(code).then(res => {
					columns.value = [columns.value[0], res]
					uPickerRef.value.setColumnValues(1, res)
					resolve()
				}).catch(() => {
					reject()
				})
			}).catch(() => {
				reject()
			})
		})
	}
	let addressComputed = ref<number[]>([])
	watch(() => formData.value.province, async (newValue, _oldValue) => {
		if (newValue) {
			let [name1, name2] = newValue.split('/')
			let index1 = columns.value[0].findIndex(i => i.name == name1)
			if (index1 != -1) {
				let index2: number = 0
				let { code } = columns.value[0][index1]
				let res = await getProvinceCity(code)
				uPickerRef.value.setColumnValues(1, res)
					index2 = res.findIndex(i => i.name == name2)
					setTimeout(() => {
						uPickerRef.value.setIndexs([index1, index2])
					}, 500)
			}


		}
	})

	
	let changeHandler = (e) => {
		let [{ code }] = e.value
		getProvinceCity(code).then(res => {
			columns.value.splice(1, 1, res)
		})
	}
	let confirmHandler = (e) => {
		let [{ name }, { name: name2 }] = e.value
		formData.value.province = name + "/" + name2
		show.value = false
	}



	//提交表单
	let addProjectHandle = (type ?: string) : Promise<void> => {
		return new Promise((resolve, reject) => {
			addUser(formData.value).then(res => {
				let { code, enterpriseId } = res as any
				if (code == 200) {
					uni.showToast({
						title: '提交成功!'
					})
					setTimeout(() => {
						let { enterpriseId: formId } = formData.value
						if (type == 'linktoDetailPage') {

							if (formId) {
								uni.navigateBack()
							} else {
								uni.redirectTo({
									url: `/pages/userItemDetail/userItemDetail?enterpriseId=${enterpriseId}`
								})
							}
						} else {
							uni.redirectTo({
								url: `/pages/addProject/index?enterpriseId=${enterpriseId}`
							})
						}


					}, 1000)

					resolve()
				} else {
					reject()
				}
			}).catch(() => {
				reject()
			})
		})

	}

	//提交表单
	let confirmHandle = (type : string) : void => {
		formRef.value.validate().then(valid => {
			if (valid) {
				addProjectHandle(type)
			} else {
			}
		}).catch((err) => {
			// 处理验证错误  
			let [target] = err
			if (target) {
				uni.showToast({
					title: target.message,
					icon: 'none'
				})
			}
		});
	}



	//获取详情
	let getEnterpriseItem = (enterpriseId : string) : void => {
		enterpriseItem(enterpriseId).then(res => {
			let { data } = res as any
			data.deptId = String(data.deptId)
			formData.value = data

		})
	}

	//获取所有省
	let getProvinceCity = (code : string) : Promise<any[]> => {
		return new Promise((resolve, reject) => {
			provinceCity(code).then(res => {
				let { rows } = res as any
				resolve(rows)
			}).catch(() => {
				reject()
			})
		})

	}



	onLoad((e) => {
		let { enterpriseId } = e as any
		//获取详情 - 编辑的场景
		init().then(() => {
			if (enterpriseId) {
				getEnterpriseItem(enterpriseId)
			}
		})

	})
	onMounted(() => {
		formRef.value.setRules(rules)
		getContactTitleList()
		getEnterpriseList()
		getEnterpriseSourceList()

	})
</script>

<script lang="ts">
	export default {
		options: {
			styleIsolation: 'shared',
		}
	}
</script>

<style lang="scss" scoped>
	.page-content {
		width: 100%;
		height: 100%;
		background: rgb(246, 246, 248);

		.page-main {
			display: block;
			flex: 1;
			width: 100%;
			padding: 20rpx;
			box-sizing: border-box;

			.projectInformation {
				background: #fff;
				border-radius: 6rpx;
				box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
				margin-bottom: 20rpx;
			}

			.operateRroup {
				margin: 40rpx;
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: space-around;

				.operateBtn {
					flex: 1;
					padding: 0 20rpx;
					box-sizing: border-box;
				}
			}

			.title {
				text-align: center;
				font-weight: bold;
				padding: 30rpx 0;
				border-bottom: 2rpx solid rgba(235, 235, 237, 0.5);
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: center;

				.red {
					color: #ec2f8a;
				}

				.blue {
					color: #364094;
				}

				.text {
					margin: 0 20rpx;
				}
			}

			.main {
				padding: 20rpx;
				box-sizing: border-box;
			}
		}



		::v-deep .u-form-item__body__left__content__required {
			left: 0;
		}
	}
</style>